/*
 * Copyright (c) 2016 MariaDB Corporation Ab
 * Copyright (c) 2023 MariaDB plc, Finnish Branch
 *
 * Use of this software is governed by the Business Source License included
 * in the LICENSE.TXT file and at www.mariadb.com/bsl11.
 *
 * Change Date: 2027-04-10
 *
 * On the date above, in accordance with the Business Source License, use
 * of this software will be governed by version 2 or later of the General
 * Public License.
 */

/**
 * Covers the following bugs:
 * MXS-2878: Monitor connections do not insist on SSL being used
 * MXS-2896: Server wrongly in Running state after failure to connect
 */

#include <maxtest/testconnections.hh>
#include <maxbase/format.hh>

using std::string;

void test_main(TestConnections& test);

int main(int argc, char** argv)
{
    TestConnections test;
    return test.run_test(argc, argv, test_main);
}

void test_main(TestConnections& test)
{
    auto& mxs = *test.maxscale;
    auto& repl = *test.repl;
    const std::string DROP_IN_DIR = "/etc/systemd/system/mariadb.service.d";
    mxs.check_servers_status(mxt::ServersInfo::default_repl_states());
    mxs.stop();

    if (test.ok())
    {
        for (int i = 0; i < repl.N; i++)
        {
            repl.stop_node(i);
            repl.ssh_output("mkdir -p " + DROP_IN_DIR, i);
            repl.ssh_output("echo [Service]|sudo tee " + DROP_IN_DIR + "/no-ssl.conf", i);
            repl.ssh_output("echo Environment=MYSQLD_OPTS=--skip-ssl "
                            "|sudo tee -a " + DROP_IN_DIR + "/no-ssl.conf", i);
            repl.ssh_output("systemctl daemon-reload", i);
            repl.start_node(i);
        }

        if (test.ok())
        {
            mxs.start();
            mxs.wait_for_monitor();
            auto down = mxt::ServerInfo::DOWN;
            auto status = mxs.get_servers();
            status.print();
            status.check_servers_status({down, down, down, down});
            mxs.stop();
        }

        for (int i = 0; i < repl.N; i++)
        {
            repl.stop_node(i);
            repl.ssh_output("rm " + DROP_IN_DIR + "/no-ssl.conf", i);
            repl.ssh_output("systemctl daemon-reload", i);
            repl.start_node(i);
        }

        mxs.start();
        mxs.wait_for_monitor();
        auto status = mxs.get_servers();
        status.print();
        status.check_servers_status(mxt::ServersInfo::default_repl_states());
    }
}
